package mrpanyu.guitool.example;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import mrpanyu.guitool.base.annotation.Action;
import mrpanyu.guitool.base.annotation.Parameter;
import mrpanyu.guitool.base.annotation.ToolModel;
import mrpanyu.guitool.base.model.ParameterType;
import mrpanyu.guitool.base.model.Tool;

/**
 * Another tool to count lines in file, with simplest annotations.
 * 
 * @author panyu
 *
 */
@ToolModel(displayName = "Line Counter")
public class LineCounter {

	@Parameter(displayName = "File", order = 0, type = ParameterType.FILE)
	private File file;

	@Parameter(displayName = "Encoding", order = 1)
	private String encoding = "UTF-8";

	@Action(displayName = "Count")
	public void count(Tool tool) {
		if (file == null || !file.exists()) {
			tool.errorMessage("File not exist.");
			return;
		}
		int count = 0;
		try (FileInputStream fin = new FileInputStream(file);
				InputStreamReader r = new InputStreamReader(fin, encoding);
				BufferedReader reader = new BufferedReader(r)) {
			while (reader.readLine() != null) {
				count++;
			}
			tool.infoMessage(count + " lines.");
		} catch (IOException e) {
			tool.errorMessage(e);
		}
	}

}
